import { ref, toRaw } from 'vue'
import { messageApi, contextHolder } from '@/utils/MessageUtils.js'
import service from '@/rpc/httpUtils.js'
import CONSTANTS from '@/constants/Constants.js'
import appData from '@/hooks/pmpData.js'
import cfg from '@/hooks/cfg.js'


// 专题界面
import eva from '@/components/topic/eva.vue'
import investmentBenefit from '@/components/topic/investmentBenefit.vue'
import expectedMonetaryValue from '@/components/topic/expectedMonetaryValue.vue'
import regret from '@/components/topic/regret.vue'
import projectPortfolioAndProgram from '@/components/topic/projectPortfolioAndProgram.vue'

// 专题界面Map 
const topicMap = {
  eva: {
    title: 'EVA挣值分析',
    desc:'PV,AC,EV,SV,SPI,CV,CPI,BAC,ETC,EAC,VAC,TCPI',
    c: eva
  },

  investmentBenefit:{
    title:'投资回收期',
    desc:'投资回收期',
    c:investmentBenefit
  },
  expectedMonetaryValue:{
    title:'预期货币值',
    desc:'预期货币值',
    c:expectedMonetaryValue
  },
  regret:{
    title:'后悔值',
    desc:'后悔值',
    c:regret
  },
  projectPortfolioAndProgram:{
    title:'项目组合与项目集',
    desc:'项目组合与项目集',
    c:projectPortfolioAndProgram
  }
}



// PMP字典Map
const pmpDict = ref({})
// 五大过程组列表
const processGroupList = ref([])
// 十大知识领域列表
const knowledgeAreaList = ref([])
// 五十个过程列表
const processList = ref([])
// 八大绩效域列表
const performanceDomainList = ref({})
// 技术工具列表
const techToolList = ref({})
// 输入输出列表
const ioList = ref({})
// 小词板列表
const subList = ref({})


// 五大过程组Map
const processGroupMap = ref({})
// 十大知识领域Map
const knowledgeAreaMap = ref({})
// 五十个过程Map
const processMap = ref({})
// 过程分组
const processBelong = ref({})
// 八大绩效域
const performanceDomainMap = ref({})
// 技术工具列表
const techToolMap = ref({})
// 输入输出列表
const ioMap = ref({})
// 小词板列表
const subMap = ref({})


// 高亮显示
const highLight = ref('-')
function focusHighLight(hl) {
  highLight.value = hl
}

// 高亮
const currentIO = ref('-')

function focusIO(ioId) {
  currentIO.value = ioId
}

// 高亮过滤
const hhList = ref([])

// 高亮过滤函数

// 过程名称做匹配
const processLeftMatch = function (k) {
  const r = []
  processList.value.forEach((item) => {
    if (item.nameCn.indexOf(k) == 0) {
      r.push(item.id)
    }
  })
  hhList.value = r
}

// 过程名称做匹配
const processMatch = function (k) {
  const r = []
  processList.value.forEach((item) => {
    if (item.nameCn.indexOf(k) != -1) {
      r.push(item.id)
    }
  })
  hhList.value = r
}

// 输出三大基准的过程
const processOutputThreeBenchmark = function () {
  hhList.value = ['pCreateWbs', 'pDevelopProcessPlan', 'pDevelopBudget']
}
// 三大登记册
const processOutputRegister = function () {
  hhList.value = [
    'pIdentifyRisk',
    'pIdentifyStakeholder',
    'pManageProjectKnowledge',
  ]
}

// 四个报告
const processOutputReport = function () {
  hhList.value = [
    'pIdentifyRisk',
    'pManageQuality',
    'pCloseProjectOrPhase',
    'pMonitorProjectWork'
  ]
}

// 三个日志
const processOutputLog = function () {
  hhList.value = ['pDirectProject', 'pDevelopProjectCharter','pManageStakeholderParticipation']
}

function clearHh() {
  hhList.value = []
}

// 清理缓存
async function clearPmpCache() {
  pmpDict.value = {}
  processGroupList.value = []
  knowledgeAreaList.value = []
  processList.value = []
  performanceDomainList.value = []
  techToolList.value = []
  ioList.value = []
  subList.value = []

  processGroupMap.value = {}
  knowledgeAreaMap.value = {}
  processMap.value = {}
  processBelong.value = {}
  performanceDomainMap.value = {}
  techToolMap.value = {}
  ioMap.value = {}
  subMap.value = {}
}

// 初始化PMP字典
async function initPmpDict() {

  let pmpData = {}
  if(cfg.loadDataType=='LOCAL'){
    console.info('数据加载方式：本地')
    pmpData = appData;
    messageApi.success("数据加载成功[方式：本地]")
  }

  if(cfg.loadDataType=='REMOTE'){
    console.info('数据加载方式：远程')
    try{
      const res = await service.get('/pmp/getAllDict')
      pmpData = res.result;
      messageApi.success("数据加载成功[方式：远程]")
    }catch(e){
      console.error('远程字典加载失败,使用本地字典')
      pmpData = appData;
      messageApi.info("远程数据加载失败,使用本地方式加载")
    }
  }

  // console.log("=====ttttt=======",appData)
 
  
  
  pmpDict.value = pmpData
  // console.log("=====pmpDict.value=======",toRaw(pmpData.value))
  const pgList = []
  const kaList = []
  const pList = []
  const dList = []
  const ttList = []
  const iList = []
  const sList = []

  const pmap = {}

  function sortFn(a, b) {
    return a.order - b.order
  }
  Object.values(pmpData).forEach((item) => {
    // console.log(item)
    if (CONSTANTS.itemClassify.PROCESS_GROUP == item.classify) {
      pgList.push(item)
      processGroupMap.value[item.id] = item
    }

    if (CONSTANTS.itemClassify.KNOWLEDGE_AREA == item.classify) {
      kaList.push(item)
      knowledgeAreaMap.value[item.id] = item
    }

    if (CONSTANTS.itemClassify.PROCESS == item.classify) {
      pList.push(item)
      processMap.value[item.id] = item
    }

    if (CONSTANTS.itemClassify.TECH_TOOL == item.classify) {
      ttList.push(item)
      techToolMap.value[item.id] = item
    }

    if (CONSTANTS.itemClassify.IO == item.classify) {
      iList.push(item)
      ioMap.value[item.id] = item
    }

    if (CONSTANTS.itemClassify.SUB == item.classify) {
      sList.push(item)
      subMap.value[item.id] = item
    }


    if (CONSTANTS.itemClassify.PERFORMANCE_DOMAIN == item.classify) {
      dList.push(item)
      performanceDomainMap.value[item.id] = item
    }

    pgList.sort(sortFn)
    kaList.sort(sortFn)
    dList.sort(sortFn)

    processGroupList.value = pgList
    knowledgeAreaList.value = kaList
    processList.value = pList
    performanceDomainList.value = dList
    techToolList.value = ttList
    ioList.value = iList
    subList.value = sList

    pgList.forEach((pg) => {
      pmap[pg.id] = {}

      kaList.forEach((ka) => {
        pmap[pg.id][ka.id] = []
        pList.forEach((p) => {
          if (p.belongKnowledgeArea == ka.id && p.belongProcessGroup == pg.id) {
            pmap[pg.id][ka.id].push(p)
          }
        })
      })
    })

    pgList.forEach((pg) => {
      pmap[pg.id] = {}
      kaList.forEach((ka) => {
        pmap[pg.id][ka.id] = []
        pList.forEach((p) => {
          if (p.belongKnowledgeArea == ka.id && p.belongProcessGroup == pg.id) {
            pmap[pg.id][ka.id].push(p)
          }
        })
      })
    })

    pgList.forEach((pg) => {
      kaList.forEach((ka) => {
        if (pmap[pg.id][ka.id]) {
          pmap[pg.id][ka.id].sort(sortFn)
        }
      })
    })

    processBelong.value = pmap




  })

  //   service.get('/pmp/getAllDict').then((res) => {
  //     console.log(res)
  //     pmpDict.value = res.result
  //   })
}


function searchPmpDictLocal(k, itemClassify) { 
  if(!itemClassify){
    itemClassify = Object.keys(cfg.dataType).join(",")
  }
  const dataMap = toRaw(pmpDict.value)
  const kw = k.toLowerCase();
  
  // console.log("====",kw)
  const r = [];

  for(const item in dataMap){
    if(
      !k ||
      (!!dataMap[item].nameCn && dataMap[item].nameCn.toLowerCase().indexOf(kw) >= 0) || 
      (!!dataMap[item].nameEn && dataMap[item].nameEn.toLowerCase().indexOf(kw) >= 0) || 
      (!!dataMap[item].keyword && dataMap[item].keyword.toLowerCase().indexOf(kw) >= 0)
    ){
      r.push(dataMap[item])
    }
  }
  // console.log(r)
  if(r.length >= 0){
    const result = {}
    for(const c in cfg.dataType){
      result[c] = {
        label: cfg.dataType[c].nameCn,
        options:[]
      }
    }

    r.forEach(item => {
      result[item.classify].options.push({
        label: item.nameCn + "(" + item.keyword + ")",
        value: item.id
      })
    });

    const res = []
    for(const item in result){
      //console.log("--",itemClassify,item)
      if(itemClassify.indexOf(item) >= 0){
        res.push(result[item])
      }
    } 

    //console.log('本地结果：',res)
    return res;

  }
  return []


}
// 搜索PMP字典
async function searchPmpDict(k, itemClassify) {
  if(cfg.loadDataType=='LOCAL'){
    return searchPmpDictLocal(k, itemClassify)
  }

  if(cfg.loadDataType=='REMOTE'){
    const res = await service.post(`/pmp/queryPmpDict`, { k, itemClassify })
    // console.log(res.result)
    return res.result
  }


}

// 根据id查询基本信息
async function loadPmpDict(id) {
  //   const res = await service.get(`/pmp/loadPmpDict/${id}`)
  //   console.log(res.result)
  //   return res.result
  return loadPmpDictDetail(id)
}

// 加载字典分类
async function loadClassifyDict(classify) {

  if(cfg.loadDataType=='LOCAL'){
    return cfg.dataType[classify].nameCn + "(" + cfg.dataType[classify].nameEn + ")"
  }

  if(cfg.loadDataType=='REMOTE'){
    const res = await service.get(`/pmp/loadClassifyDict/${classify}`)
    return res.msg
  }
  // const res = await service.get(`/pmp/loadClassifyDict/${classify}`)
  // return res.msg
}

// 重新加载字典
async function initPmpDataByHardCode() {
  const res = await service.get(`/ass/initPmpDataByHardCode`)
  return res.msg
}

// 备份字典
async function writePmpDataToJsonFile() {
  const res = await service.post(`/ass/writePmpDataToJsonFile`, {
    k: 'D://pmpdata.json',
  })

  return res.msg
}

// 读取字典
async function initPmpDataByJsonFile() {
  const res = await service.post(`/ass/initPmpDataByJsonFile`, {
    k: 'D://pmpdata.json',
  })
  return res.msg
}
async function initPmpDataByDb() {
  const res = await service.post(`/ass/initPmpDataByDb`, {})
  return res.msg
}



// 清空前端pmp字典
function clearPmpDataCache() {
  pmpDict.value = {}
}

// 获取明细
function loadPmpDictDetail(id) {
  
  const pmpDictItem = toRaw(pmpDict.value)

  // console.log('toRaw:', pmpDictItem)
  const item = pmpDictItem[id]

  
  if (!item) {
    console.log('========', id, 'can not found classify')
    messageApi.success(`${id} can not found classify`)
  }

  try{
    const c = item.classify
  }catch(e){
     alert(`${id}未找到classify属性`)
  }
  if ('PROCESS_GROUP' == item.classify) {
    Object.values(pmpDictItem).forEach((ka) => {
      if (ka.classify == 'KNOWLEDGE_AREA') {
        item[ka.id] = []
        Object.values(pmpDictItem).forEach((process) => {
          // console.log('|||', process, item.id, ka.id)
          if (
            process.classify == 'PROCESS' &&
            process.belongProcessGroup == item.id &&
            process.belongKnowledgeArea == ka.id
          ) {
            item[ka.id].push(process.id)
          }
        })
      }
    })
  }
  if ('KNOWLEDGE_AREA' == pmpDictItem.classify) {
  }
  if ('TECH_TOOL' == pmpDictItem.classify) {
  }
  if ('IO' == pmpDictItem.classify) {
  }

  return item
}

// 保存PmpItem

async function insertPmpItem(pmpItem){
  const res = await service.post(`/pmp/insertPmpItem`, pmpItem)
  return res
}

// 查询PmpItem的关系
async function queryRelaIds(pmpItemId,relaClassify){
  const res = await service.get(`/pmp/queryRelaIds/${pmpItemId}/${relaClassify}`)
  return res
}

// 根据id查询PmpItem
async function queryPmpItemById(pmpItemId){
  const res = await service.get(`/pmp/queryPmpItemById/${pmpItemId}`)
  return res
}

// 查询引用了某个PmpItem的PmpItem
async function queryReferenceList(relaId,relaClassify){
  const res = await service.get(`/pmp/queryReferenceList/${relaId}/${relaClassify}`)
  return res
}

// 添加小词
async function insertSubRela(mainId,relaId){
  const res = await service.get(`/pmp/insertSubRela/${mainId}/${relaId}`)
  return res
}

// 修改pmpItem
async function updatePmpItemDefineInfo(pmpItemDto){
  const res = await service.post(`/pmp/updatePmpItemDefineInfo`,pmpItemDto)
  return res
}

// 查询pmpItem的markdown
async function queryPmpItemMdById(pmpItemId){
  const res = await service.get(`/pmp/queryPmpItemMdById/${pmpItemId}`)
  return res
}

// 保存pmpItem的markdown
async function savePmpItemMd(pmpItemMd){
  const res = await service.post(`/pmp/savePmpItemMd`,pmpItemMd)
  return res
}

// 查询涉及词
async function queryPmpReferList(pmpItemId){
  const res = await service.get(`/pmp/queryPmpReferList/${pmpItemId}`)
  return res
}

// 添加涉及词
async function addPmpRefer(mainId,relaId){
  const res = await service.get(`/pmp/addPmpRefer/${mainId}/${relaId}`)
  return res
}



// 全文检索
async function queryPmpItemFullText(kw){
  const res = await service.post(`/pmp/queryPmpItemFullText`,{k:kw})
  return res
}

// 带有匹配分类的全文检索
async function queryPmpItemFullTextWithClassify(kw){
  const res = await service.post(`/pmp/queryPmpItemFullTextWithClassify`,{k:kw})
  return res
}
// 搜索专题
async function queryTopic(){
  const res = await service.get(`/pmp/queryTopic`)
  return res
}

// 修改专题
async function changeTopic(id,isTopic){
  const res = await service.get(`/pmp/changeTopic/${id}/${isTopic}`)
  return res
}

// itto引用统计
async function queryPmpIttoStatictisicList(relaClassify){
  const res = await service.get(`/pmp/queryPmpIttoStatictisicList/${relaClassify}`)
  return res
}

// 编辑关系md
async function editRelaMd(mainId,relaId,classify,md){
  const res = await service.post(`/pmp/editRelaMd`,{
    mainId,
    relaId,
    classify,
    md
  })
  return res
}

// 查询关系md
async function queryRelaMd(mainId,relaId,classify){
  const res = await service.post(`/pmp/queryRelaMd`,{
    mainId,
    relaId,
    classify
  })
  return res
}

// 关系md是否有描述
async function queryHasRelaMd(mainId,relaId,classify){
  const res = await service.post(`/pmp/queryHasRelaMd`,{
    mainId,
    relaId,
    classify
  })
  return res
}

// 查询绩效域信息
async function queryPmpPerformanceDomainDtoByPmpItemId(pmpItemId){
  const res = await service.get(`/pmp/queryPmpPerformanceDomainDtoByPmpItemId/${pmpItemId}`)
  return res
}






const APPENV = {
  env:import.meta.env,
  isDev:import.meta.env.MODE == 'dev',
  // isDev:false,
  isProd :import.meta.env.MODE == 'prod'
}




export default {
  pmpDict,
  processGroupList,
  knowledgeAreaList,
  processList,
  performanceDomainList,
  techToolList,
  ioList,
  subList,
  subMap,
  ioMap,
  techToolMap,
  processGroupMap,
  knowledgeAreaMap,
  processMap,
  processBelong,
  performanceDomainMap,
  highLight,
  hhList,
  currentIO,
  topicMap,
  focusIO,
  focusHighLight,
  initPmpDict,
  searchPmpDict,
  loadPmpDict,
  loadClassifyDict,
  initPmpDataByHardCode,
  writePmpDataToJsonFile,
  initPmpDataByJsonFile,
  initPmpDataByDb,
  clearPmpDataCache,
  loadPmpDictDetail,

  APPENV,

  processLeftMatch,
  processMatch,
  processOutputThreeBenchmark,
  processOutputRegister,
  processOutputReport,
  processOutputLog,
  clearHh,

  insertPmpItem,
  queryRelaIds,
  queryPmpItemById,
  queryReferenceList,
  insertSubRela,
  updatePmpItemDefineInfo,
  queryPmpItemMdById,
  savePmpItemMd,
  queryPmpReferList,
  addPmpRefer,
  queryPmpItemFullText,
  queryPmpItemFullTextWithClassify,
  queryTopic,
  changeTopic,
  queryPmpIttoStatictisicList,
  editRelaMd,
  queryRelaMd,
  queryHasRelaMd,
  queryPmpPerformanceDomainDtoByPmpItemId
}
